package org.one.afternoon.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.one.afternoon.common.Result;
import org.one.afternoon.domain.Record;
import org.one.afternoon.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/record")
@Slf4j
public class RecordController {

    @Autowired
    private RecordService recordService;


    @CrossOrigin
    @GetMapping("/getAll")
    private Result<List<Record>> getAll() {
        return Result.success(recordService.list());
    }

    @CrossOrigin
    @PostMapping("/insertOne")
    @ResponseBody
    private Result<Boolean> insertOne(@RequestBody Record record) {
        return Result.success(recordService.save(record));
    }

    @CrossOrigin
    @PostMapping("/getOne")
    @ResponseBody
    private Result<Record> getOne(@RequestParam String question, String text) {
        LambdaQueryWrapper<Record> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (question == null) {
            lambdaQueryWrapper.like(StringUtils.isNotBlank(text), Record::getAnswer, text);
            if (recordService.list(lambdaQueryWrapper) == null || recordService.list(lambdaQueryWrapper).isEmpty()) {
                return Result.error("No records found");
            }
            return Result.success(recordService.list(lambdaQueryWrapper).get(0));
        }
        lambdaQueryWrapper.like(StringUtils.isNotBlank(question), Record::getQuestion, question);
        if (recordService.list(lambdaQueryWrapper) == null || recordService.list(lambdaQueryWrapper).isEmpty()) {
            return Result.error("No records found");
        }
        return Result.success(recordService.list(lambdaQueryWrapper).get(0));
    }

}
